package com.juyu.miliao.api.config;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.properties.ElasticsearchUri;
import com.juyu.miliao.api.properties.MiLiaoApiProperties;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.*;

/**
 * @author xuanqicheng
 */
@Configuration
public class ElasticsearchConfig {
    @Autowired
    private MiLiaoApiProperties miLiaoApiProperties;


    @Bean
    public RestHighLevelClient restHighLevelClient(){

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(miLiaoApiProperties.getElasticsearch().getUsername(),
                        miLiaoApiProperties.getElasticsearch().getPassword()));

        HttpHost[]hosts = miLiaoApiProperties.getElasticsearch().getUris().stream().map(this::httpHost)
                .filter(Objects::nonNull)
                .toArray(HttpHost[]::new);

         RestClientBuilder builder=RestClient.builder(hosts)
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        return new RestHighLevelClient(builder);
    }


    private HttpHost httpHost(ElasticsearchUri elasticsearchUri) {

        if(elasticsearchUri!=null){
            String ip = elasticsearchUri.getIp();
            int port = elasticsearchUri.getPort();
            if(StringUtils.isNotBlank(ip)){
                return new HttpHost(ip, port, "http");
            }else{
                return null;
            }
        }else{
            return null;
        }

    }
}
